/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package estg.dae.projecto.bank.utils;

import estg.dae.projecto.bank.model.BrokerSettings;
import estg.dae.projecto.broker.controllers.IBrokerControllerRemote;
import java.util.Properties;
import javax.jms.Queue;
import javax.jms.QueueConnectionFactory;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author Marco
 */
public class BrokerServiceLocator {

    public static IBrokerControllerRemote getBrokerService() throws Exception {
        try {
            BrokerSettings brokerSettings = BrokerSettings.getInstance();
            return (IBrokerControllerRemote) remoteLookup(brokerSettings.getHostName()
                    , brokerSettings.getServicePort()
                    , IBrokerControllerRemote.class.getName());
        } catch (NamingException error) {
            error.printStackTrace();
            return null;
        }
    }

    public static QueueConnectionFactory getRemoteQueueConnectionFactory()
            throws Exception {
        BrokerSettings brokersettings = BrokerSettings.getInstance();
        return (QueueConnectionFactory) remoteLookup(brokersettings.getHostName()
                , brokersettings.getServicePort()
                , brokersettings.getConnectionFactory());
    }

    public static Queue getRemoteQueue()
            throws Exception {
        BrokerSettings brokersettings = BrokerSettings.getInstance();

        return (Queue) remoteLookup(brokersettings.getHostName()
                , brokersettings.getServicePort()
                , brokersettings.getMessageQueue());
    }

    private static Object remoteLookup(
            String host,
            int port,
            String jndiName)
            throws Exception {

        InitialContext context = null;

        Properties props = new Properties();
        props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.enterprise.naming.SerialInitContextFactory");
        props.setProperty(Context.STATE_FACTORIES,
                "java.naming.factory.state");
        props.setProperty(Context.URL_PKG_PREFIXES,
                "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
        props.setProperty("org.omg.CORBA.ORBInitialHost",
                host);
        props.setProperty("org.omg.CORBA.ORBInitialPort",
                Integer.toString(port));

        try {

            context = new InitialContext(props);
            return context.lookup(jndiName);

        } catch (NamingException ne) {
            throw new Exception("JNDI Service not found at location: " + host + ":" + port);
        }

    }
}
